package cn.wolfcode.wolf2w.advice;

import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.wolfcode.wolf2w.util.JsonResult.CODE_ERROR_PARAM;

@ControllerAdvice
public class Wolf2wExceptionHandler {

    // 处理异常方法跟请求映射方法一样
    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult logicExceptionHandler(LogicException le, HttpServletResponse resp){
        le.printStackTrace();
        // 考虑响应回去可能会出现中文乱码问题
        resp.setContentType("application/json;charset=utf-8");
        return JsonResult.error(CODE_ERROR_PARAM,le.getMessage(),null);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult exceptionHandler(Exception e, HttpServletResponse resp){
        e.printStackTrace();
        // 考虑响应回去可能会出现中文乱码问题
        resp.setContentType("application/json;charset=utf-8");
        return JsonResult.defaultError();
    }
}
